package maquinavotar.dao;

import maquinavotar.common.Election;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class VoteDAOImplXml implements VoteDAO {

    private String path = "data_io/voto.xml";
    
    public void saveVoto(ArrayList<Election> vote) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            DOMImplementation implementation = builder.getDOMImplementation();
            Document document = implementation.createDocument(null, "voto", null);
            document.setXmlVersion("1.0"); // asignamos la version de nuestro XML
            
            Element raiz = document.getDocumentElement();
            
            for(Election choice : vote) {
                Element elemento = document.createElement("eleccion");
                
                Element id = document.createElement("nombre");
                id.appendChild(document.createTextNode(choice.name));
                elemento.appendChild(id);
                
                Element post = document.createElement("puesto");
                post.appendChild(document.createTextNode(choice.post));
                elemento.appendChild(post);
                
                raiz.appendChild(elemento);
            }
            
            Source source = new DOMSource(document);
            Result result = new StreamResult(new java.io.File(path)); // nombre del archivo
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.transform(source, result);
        } catch(Exception e){
            System.out.println("Error: "+e);
        }
    }
    
}
